import Router from 'koa-router'
import { Blog, Comment } from '../db/index.js'

const router = new Router()

// API：发表博客
router.post('/blog', async (ctx) => {
  if (!ctx.session.isSignIn) {
    return ctx.rr('发表博客失败，请登录后再重试！')
  }
  const body = ctx.request.body
  const blog = new Blog({ ...body, author: ctx.session.user._id })
  await blog.save()
  ctx.cc()
})

// API：发表评论
router.post('/comment', async (ctx) => {
  if (!ctx.session.isSignIn) {
    return ctx.rr('发表评论失败！')
  }
  const body = ctx.request.body

  const cmt = new Comment({ ...body, user: ctx.session.user._id })
  await cmt.save()
  const newCmt = await Comment.findOne({ _id: cmt._id }).populate('user')
  ctx.cc(newCmt, '评论发表成功！')
})

// API：删除博客
router.delete('/blog/:id', async (ctx) => {
  if (!ctx.session.isSignIn) {
    return ctx.rr('删除博客失败！')
  }
  const id = ctx.params.id
  await Blog.deleteOne({ _id: id })
  await Comment.deleteMany({ blog: id })
  return ctx.cc()
})

// API：修改博客
router.put('/blog/:id', async (ctx) => {
  if (!ctx.session.isSignIn) {
    return ctx.rr('修改博客失败！')
  }
  const id = ctx.params.id
  const body = ctx.request.body

  await Blog.updateOne({ _id: id }, { ...body, lastUpdateAt: Date.now() })
  return ctx.cc()
})

export default router
